#include "RenderBuffer.hpp"

namespace zzz{
Renderbuffer::Renderbuffer(GLenum internalFormat)
:buf_(0), width_(0), height_(0),
internal_format_(internalFormat)
{
}

Renderbuffer::Renderbuffer(GLenum internalFormat, int width, int height)
:buf_(0)
{
  Create(internalFormat, width, height);
}

Renderbuffer::~Renderbuffer()
{
  if (IsValid())
    glDeleteRenderbuffers(1, &buf_);
}

void Renderbuffer::Create(int width, int height)
{
  Create(internal_format_, width, height);
}

void Renderbuffer::Create(GLenum internal_format, int width, int height)
{
  if (width==width_ && height==height_ && internal_format_==internal_format) return;
  static const int maxSize = Renderbuffer::GetMaxSize();
  if (width > maxSize || height > maxSize) {
    ZLOGV << "Cannot create RenderBuffer, too large size: "
      << width << "x" << height << ", max size is "<<maxSize<<endl;
    return;
  }

  // Guarded bind
  Bind();

  // Allocate memory for renderBuffer
  glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, internal_format, width, height);
  width_=width;
  height_=height;
  internal_format_=internal_format;

  Unbind();
}

GLint Renderbuffer::GetMaxSize()
{
  GLint maxAttach = 0;
  glGetIntegerv(GL_MAX_RENDERBUFFER_SIZE, &maxAttach);
  return maxAttach;
}

}  // namespace zzz